package com.chinaunicom.order.app.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * @author guomenghuai
 * @date 2023/12/11
 * @Description
 */
@Configuration
@MapperScan({"com.chinaunicom.order.infrastructure.database.mapper"})
public class MybatisPlusConfig {

    /**
     * 公共字段填充
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                if (metaObject.hasSetter("createTime")) {
                    Object createTime = getFieldValByName("createTime", metaObject);
                    if (createTime == null) {
                        setFieldValByName("createTime", new Date(), metaObject);
                    }
                }
                if (metaObject.hasSetter("updateTime")) {
                    Object createTime = getFieldValByName("updateTime", metaObject);
                    if (createTime == null) {
                        setFieldValByName("updateTime", new Date(), metaObject);
                    }
                }
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                setFieldValByName("updateTime", new Date(), metaObject);
            }
        };
    }

    /**
     * 分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor paginationInterceptor = new MybatisPlusInterceptor();
        paginationInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return paginationInterceptor;
    }

}
